from approval_service.approval.mappers.advance_approval_mapper import AdvanceApprovalMapper
from approval_service.approval.mappers.approval_mapper import ApprovalMapper
from approval_service.approval.mappers.reimbursement_approval_fi_mapper import ReimbursementApprovalFiMapper
from approval_service.approval.mappers.reimbursement_approval_ma_mapper import ReimbursementApprovalMaMapper
from approval_service.approval.mappers.travel_approval_mapper import TravelApprovalMapper
from approval_service.approval.service.client.reimbursement_client import ReimbursementClient
from approval_service.approval.service.client.travel_client import TravelClient
from approval_service.approval.service.client.user_client import UserClient
from commons.entity.enum.advance_approval_enum import AdvanceApprovalEnum
from commons.entity.enum.reimbursement_approval_enum import ReimbursementApprovalEnum
from commons.entity.enum.travel_approval_enum import TravelApprovalEnum
from commons.entity.po.advance_approval import AdvanceApproval
from commons.entity.po.approval import Approval
from commons.entity.po.reimbursement_approval_fi import ReimbursementApprovalFi
from commons.entity.po.reimbursement_approval_ma import ReimbursementApprovalMa
from commons.entity.po.travel_approval import TravelApproval
from commons.entity.query.advance_approval_query import AdvanceApprovalQuery
from commons.entity.query.approval_query import ApprovalQuery
from commons.entity.query.reimbursement_approval_fi_query import ReimbursementApprovalFiQuery
from commons.entity.query.reimbursement_approval_ma_query import ReimbursementApprovalMaQuery
from commons.entity.query.travel_approval_query import TravelApprovalQuery
from commons.entity.vo.pagination_result_vo import PaginationResultVO
from commons.entity.vo.reimbursement_vo import ReimbursementVO
from commons.entity.vo.travel_vo import TravelVO
from commons.exception.business_exception import BusinessException
from commons.utils.copy_tools import CopyTools
import datetime


class ApprovalService:
    def __init__(self):
        self.approval_mapper = ApprovalMapper()
        self.travel_client = TravelClient()
        self.user_client = UserClient()
        self.reimbursement_client = ReimbursementClient()
        self.travel_approval_mapper = TravelApprovalMapper()
        self.reimbursement_approval_ma_mapper = ReimbursementApprovalMaMapper()
        self.reimbursement_approval_fi_mapper = ReimbursementApprovalFiMapper()
        self.advance_approval_mapper = AdvanceApprovalMapper()

    def find_list_by_param(self, approval_query=None):
        """
        业务逻辑：根据多个参数查询审批状态列表。
        :param approval_query: ApprovalQuery 实例，包含查询过滤条件。
        :return: 包含审批状态信息字典的列表。
        """
        print("ApprovalService find_list_by_param")
        print(approval_query)

        return self.approval_mapper.select_list(Approval, approval_query)

    def find_count_by_param(self, approval_query=None):
        """
        业务逻辑：根据多个参数统计审批状态数量。
        :param approval_query: ApprovalQuery 实例，包含查询过滤条件。
        :return: 符合条件的审批状态数量。
        """
        print("ApprovalService find_count_by_param")
        print(approval_query)

        return self.approval_mapper.select_count(Approval, approval_query)

    def get_approval_by_approval_id(self, approval_id):
        """
        业务逻辑：获取单条审批状态信息。
        :param approval_id: str
        :return: 审批状态信息字典或 None
        """
        print("ApprovalService get_approval_by_approval_id ")
        print(approval_id)

        return self.approval_mapper.select_by_approval_id(approval_id)

    def add(self, approval_bean):
        """
        业务逻辑：添加一个新的审批状态。
        :param approval_bean: Approval 类实例，包含审批状态信息。
        :return: 插入操作是否成功（True/False）。
        """
        print("ApprovalService add approval")
        print(approval_bean)

        return self.approval_mapper.insert(approval_bean)

    def add_batch(self, approval_list_bean):
        """
        业务逻辑：批量添加审批状态。
        :param approval_list_bean: 包含多个 Approval 类实例的列表，包含需要插入的审批状态信息。
        :return: 插入操作成功的审批状态数量。
        """
        print("ApprovalService add_batch approvals")
        print(approval_list_bean)

        if not approval_list_bean:
            print("No approvals to add. The input list is either null or empty.")
            return 0

        return self.approval_mapper.insert_batch(approval_list_bean)

    def add_or_update_batch(self, approval_list_bean):
        """
        业务逻辑：批量插入或更新审批状态。
        :param approval_list_bean: 包含多个 Approval 类实例的列表，包含需要插入或更新的审批状态信息。
        :return: 插入或更新成功的审批状态数量。
        """
        print("ApprovalService add_or_update_batch approvals")
        print(approval_list_bean)

        if not approval_list_bean:
            print("No approvals to add or update. The input list is either null or empty.")
            return 0

        return self.approval_mapper.insert_or_update_batch(Approval, approval_list_bean)

    def update_by_param(self, approval_bean, approval_query):
        """
        业务逻辑：根据多个条件更新审批状态信息。
        :param approval_bean: Approval 类实例或字典，包含需要更新的字段及其新值。
        :param approval_query: ApprovalQuery 类实例或字典，包含用于定位的过滤条件。
        :return: 更新成功的数量。
        """
        print("ApprovalService update_by_param")
        print(approval_bean)
        print(approval_query)

        return self.approval_mapper.update_by_params(Approval, approval_bean, approval_query)

    def delete_by_param(self, approval_query):
        """
        业务逻辑：根据多个条件删除审批状态信息。
        :param approval_query: ApprovalQuery 类实例或字典，包含用于定位的过滤条件。
        :return: 删除成功的数量。
        """
        print("ApprovalService delete_by_param")
        print(approval_query)

        return self.approval_mapper.delete_by_param(Approval, approval_query)

    def update_approval_by_approval_id(self, approval_bean, approval_id):
        """
        业务逻辑：根据 approval_id 更新审批状态信息。
        :param approval_id: str
        :param approval_bean: Approval 类实例，包含需要更新的审批状态属性。
        :return: 更新成功信息或错误信息。
        """
        print("ApprovalService update_approval_by_approval_id ")
        print(f"approval_id: {approval_id}, approval_bean: {approval_bean}")

        return self.approval_mapper.update_by_approval_id(approval_bean, approval_id)

    def delete_approval_by_approval_id(self, approval_id):
        """
        业务逻辑：根据 approval_id 删除审批状态。
        :param approval_id: str
        :return: 删除成功或错误。
        """
        print("ApprovalService delete_approval_by_approval_id ")
        print(approval_id)

        return self.approval_mapper.delete_by_approval_id(approval_id)

    def get_approval_by_travel_id(self, travel_id):
        """
        根据 travel_id 获取对应的审批记录。
        :param travel_id: 出差 ID
        :return: 审批记录信息字典或 None
        """
        print("ApprovalService get_approval_by_travel_id")
        print(f"travel_id: {travel_id}")

        # 直接通过 travel_id 查找审批记录
        approval = self.approval_mapper.select_by_travel_id(Approval, travel_id)

        # 如果查询返回为空，说明没有找到记录
        if not approval:
            return None

        return approval  # 返回审批记录

    def get_travel_apply(self, user_id, page_no, page_size):
        """
        获取出差申请信息，分页返回。
        :param user_id: 工号
        :param page_no: 页码
        :param page_size: 每页条数
        :return: 分页结果，包含出差申请信息列表
        """
        travel_vo_list = []

        approval_statuses = [
            TravelApprovalEnum.UNPROCESSED,
            TravelApprovalEnum.APPROVED,
            TravelApprovalEnum.REJECTED
        ]

        for status in approval_statuses:
            travel_vo_list.extend(
                self.fetch_travel_vo_s_by_approval_status(status))

        # 去除自己的申请
        travel_vo_list = [
            travel_vo for travel_vo in travel_vo_list if travel_vo.user_id != user_id]

        count = len(travel_vo_list)

        # start = (page_no - 1) * page_size
        # end = start + page_size
        # if end > count:
        #     end = count
        # total_page = count // page_size if count % page_size == 0 else count // page_size + 1

        return PaginationResultVO(count, page_size, page_no, 0, travel_vo_list)

    def fetch_travel_vo_s_by_approval_status(self, status):
        """
        获取指定审批状态的出差申请信息。
        :param status: 出差审批状态
        :return: 出差申请VO列表
        """
        travel_vo_list = []

        # 创建 ApprovalQuery 实例，查询指定的出差审批状态
        approval_query = ApprovalQuery(travel_approval=status.code)
        approval_list = self.find_list_by_param(approval_query)
        approval_map = {
            approval.travel_id: approval for approval in approval_list}

        travel_id_list = list(
            set(approval.travel_id for approval in approval_list))

        if not travel_id_list:
            return travel_vo_list

        # 获取出差申请信息
        travel_list = self.travel_client.get_all_travels_by_id_list(
            travel_id_list)
        travel_list.sort(key=lambda x: x.apply_date)

        user_id_list = list(set(travel.user_id for travel in travel_list))

        # 获取用户信息
        user_list = self.user_client.get_all_users_by_id_list(user_id_list)
        user_map = {user.user_id: user for user in user_list}

        for travel in travel_list:
            travel_vo = CopyTools.copy(travel, TravelVO)

            approval = approval_map.get(travel.travel_id)
            travel_vo.travel_rejection = approval.travel_rejection
            travel_vo.approval_id = approval.approval_id
            travel_vo.travel_status = status.code
            travel_vo.travel_status_name = status.msg

            user = user_map.get(travel.user_id)
            if user:
                travel_vo.user_name = user.name
                travel_vo.user_phone = user.phone
                travel_vo.user_email = user.email
                travel_vo.position = user.position

            travel_vo.budget = (travel_vo.food_cost +
                                travel_vo.hotel_cost + travel_vo.transport_cost)

            travel_vo_list.append(travel_vo)

        return travel_vo_list

    def approve_travel_apply(self, user_id, approval_id, status, travel_rejection):
        """
        业务逻辑：审批出差申请，更新审批状态和记录审批日志。
        :param user_id: 工号
        :param approval_id: 审批ID
        :param status: 审批状态
        :param travel_rejection: 拒绝原因
        :return: 操作结果
        """
        # 获取审批信息
        approval = self.get_approval_by_approval_id(approval_id)
        approval.travel_approval = status

        if TravelApprovalEnum.REJECTED.code == status:
            if not travel_rejection or len(travel_rejection.strip()) == 0:
                raise BusinessException("请填写拒绝原因")
            approval.travel_rejection = travel_rejection

        # 更新审批信息
        result = self.update_approval_by_approval_id(approval, approval_id)

        if result == 0:
            raise BusinessException("提交信息失败")

        # 添加审批出差申请记录
        travel_approval = TravelApproval()
        travel_approval.manager_id = user_id
        travel_approval.travel_id = approval.travel_id
        travel_approval.date = datetime.date.today()

        # 查询是否已有记录
        travel_approval_query = TravelApprovalQuery()
        travel_approval_query.travel_id = approval.travel_id
        travel_approval_query.manager_id = user_id

        travel_approval_list = self.travel_approval_mapper.select_list(
            TravelApproval, travel_approval_query)

        if not travel_approval_list:
            # 无记录，新增
            result = self.travel_approval_mapper.insert(travel_approval)
        else:
            # 有记录，更新
            result = self.travel_approval_mapper.update_by_travel_approval_id(
                travel_approval, travel_approval_list[0].travel_approval_id)

        return result

    def get_advance_apply(self, user_id, page_no, page_size):
        """
        业务逻辑：获取出差申请的相关信息，分页显示，并去除自己的申请。
        :param user_id: 用户ID
        :param page_no: 当前页
        :param page_size: 每页显示的记录数
        :return: PaginationResultVO 实例，包含分页结果
        """
        travel_vo_list = []

        # 获取不同审批状态的出差申请
        advance_statuses = [
            AdvanceApprovalEnum.UNPROCESSED,
            AdvanceApprovalEnum.APPROVED,
            AdvanceApprovalEnum.REJECTED,
            AdvanceApprovalEnum.HANDLED
        ]

        for status in advance_statuses:
            travel_vo_list.extend(
                self.fetch_travel_vo_s_by_advance_status(status))

        # 去除自己的申请
        travel_vo_list = [
            travel_vo for travel_vo in travel_vo_list if travel_vo.user_id != user_id]

        count = len(travel_vo_list)

        # start = (page_no - 1) * page_size
        # end = start + page_size
        # if end > count:
        #     end = count
        #
        # total_page = count // page_size + (1 if count % page_size != 0 else 0)

        result = PaginationResultVO(
            count, page_size, page_no, 0, travel_vo_list)
        return result

    def fetch_travel_vo_s_by_advance_status(self, status):
        """
        业务逻辑：获取根据出差审批状态获取出差VO的列表
        :param status: 出差状态
        :return: 包含出差VO的列表
        """
        travel_vo_list = []

        # 查询出差申请的审批状态
        approval_query = ApprovalQuery()
        approval_query.travel_approval = TravelApprovalEnum.APPROVED.code
        approval_query.advance_approval = status.code
        approval_list = self.find_list_by_param(approval_query)

        # 按照出差ID去重
        approval_map = {
            approval.travel_id: approval for approval in approval_list}

        travel_id_list = list(
            set([approval.travel_id for approval in approval_list]))

        if not travel_id_list:
            return travel_vo_list

        # 获取出差申请信息
        travel_list = self.travel_client.get_all_travels_by_id_list(
            travel_id_list)
        travel_list.sort(key=lambda x: x.apply_date)

        user_id_list = list(set([travel.user_id for travel in travel_list]))
        user_list = self.user_client.get_all_users_by_id_list(user_id_list)
        user_map = {user.user_id: user for user in user_list}

        for travel in travel_list:
            travel_vo = CopyTools.copy(travel, TravelVO)

            approval = approval_map.get(travel.travel_id)
            travel_vo.advance_rejection = approval.advance_rejection
            travel_vo.approval_id = approval.approval_id
            travel_vo.advance_status = status.code
            travel_vo.advance_status_name = status.msg

            advance_approval_query = AdvanceApprovalQuery()
            advance_approval_query.advance_id = travel.travel_id
            advance_approval_list = self.advance_approval_mapper.select_list(
                AdvanceApproval, advance_approval_query)
            if advance_approval_list and advance_approval_list[0].payment > 0:
                travel_vo.payment = advance_approval_list[0].payment
            else:
                travel_vo.payment = None

            user = user_map.get(travel.user_id)
            travel_vo.user_name = user.name
            travel_vo.user_phone = user.phone
            travel_vo.user_email = user.email
            travel_vo.position = user.position
            travel_vo.budget = (travel_vo.food_cost +
                                travel_vo.hotel_cost + travel_vo.transport_cost)

            travel_vo_list.append(travel_vo)

        return travel_vo_list

    def approve_advance_apply(self, user_id, approval_id, payment, status, advance_rejection):
        """
        业务逻辑：审批出差申请的预支审批
        :param user_id: 用户ID
        :param approval_id: 审批ID
        :param payment: 付款金额
        :param status: 审批状态
        :param advance_rejection: 拒绝原因
        :return: 返回操作结果
        """
        # 更新出差申请状态
        approval = self.get_approval_by_approval_id(approval_id)
        approval.advance_approval = status

        if AdvanceApprovalEnum.REJECTED.code == status:
            if not advance_rejection:
                raise BusinessException("请填写拒绝原因")
            approval.advance_rejection = advance_rejection

        result = self.update_approval_by_approval_id(
            approval, approval_id)

        if result == 0:
            raise BusinessException("提交信息失败")

        # 添加审批出差申请记录
        advance_approval = AdvanceApproval()
        advance_approval.finance_id = user_id
        advance_approval.advance_id = approval.travel_id
        advance_approval.payment = payment
        advance_approval.date = datetime.date.today()

        # 查询是否已有记录
        advance_approval_query = AdvanceApprovalQuery()
        advance_approval_query.advance_id = approval.travel_id
        advance_approval_list = self.advance_approval_mapper.select_list(
            AdvanceApproval, advance_approval_query)

        if len(advance_approval_list) == 0:
            # 无记录，新增
            result = self.advance_approval_mapper.insert(advance_approval)
        else:
            # 有记录，更新
            result = self.advance_approval_mapper.update_by_advance_approval_id(
                advance_approval, advance_approval_list[0].advance_approval_id
            )

        return result

    def get_reimbursement_apply_ma(self, user_id, page_no, page_size):
        """
        获取报销申请列表（管理员）
        :param user_id: 用户ID
        :param page_no: 当前页码
        :param page_size: 每页显示的记录数
        :return: 返回分页结果
        """
        reimbursement_vo_list = []

        reimbursement_statuses = [
            ReimbursementApprovalEnum.UNPROCESSED,
            ReimbursementApprovalEnum.APPROVED,
            ReimbursementApprovalEnum.REJECTED
        ]

        for status in reimbursement_statuses:
            reimbursement_vo_list.extend(
                self.fetch_reimbursement_vo_s_by_approval_status_ma(status))

        # 去除自己的申请
        reimbursement_vo_list = [
            reimbursement for reimbursement in reimbursement_vo_list if reimbursement.user_id != user_id]

        count = len(reimbursement_vo_list)

        # start = (page_no - 1) * page_size
        # end = start + page_size
        # if end > count:
        #     end = count
        # total_page = count // page_size if count % page_size == 0 else count // page_size + 1

        result = PaginationResultVO(
            count, page_size, page_no, 0, reimbursement_vo_list)

        return result

    def fetch_reimbursement_vo_s_by_approval_status_ma(self, status):
        """
        根据审批状态获取报销申请信息
        :param status: 审批状态
        :return: 返回报销申请信息列表
        """
        reimbursement_vo_list = []

        # 查询报销申请状态，出差已被批准
        approval_query = ApprovalQuery()
        approval_query.travel_approval = TravelApprovalEnum.APPROVED.code
        approval_query.reimbursement_approval_ma = status.code
        approval_list = self.find_list_by_param(approval_query)

        approval_map = {
            approval.travel_id: approval for approval in approval_list}
        travel_id_list = list(
            set([approval.travel_id for approval in approval_list]))

        if not travel_id_list:
            return reimbursement_vo_list

        # 获取出差申请和对应的用户信息
        travel_list = self.travel_client.get_all_travels_by_id_list(
            travel_id_list)
        travel_map = {travel.travel_id: travel for travel in travel_list}

        user_id_list = list(set([travel.user_id for travel in travel_list]))
        user_list = self.user_client.get_all_users_by_id_list(user_id_list)
        user_map = {user.user_id: user for user in user_list}

        # 获取报销申请信息
        reimbursement_list = self.reimbursement_client.get_reimbursements_by_id_list(
            travel_id_list)

        for reimbursement in reimbursement_list:
            reimbursement_vo = CopyTools.copy(reimbursement, ReimbursementVO)

            reimbursement_vo.reimbursement = (
                    reimbursement.food_cost + reimbursement.hotel_cost + reimbursement.transport_cost)

            travel = travel_map.get(reimbursement.travel_id)
            reimbursement_vo.travel_reason = travel.travel_reason
            reimbursement_vo.travel_detail = travel.travel_detail
            reimbursement_vo.start_date = travel.start_date
            reimbursement_vo.end_date = travel.end_date

            user = user_map.get(travel.user_id)
            reimbursement_vo.user_id = user.user_id
            reimbursement_vo.user_name = user.name
            reimbursement_vo.user_phone = user.phone
            reimbursement_vo.user_email = user.email
            reimbursement_vo.position = user.position

            approval = approval_map.get(travel.travel_id)
            reimbursement_vo.approval_id = approval.approval_id
            reimbursement_vo.reimbursement_status = status.code
            reimbursement_vo.reimbursement_status_name = status.msg
            reimbursement_vo.reimbursement_rejection = approval.reimbursement_rejection_ma

            reimbursement_vo_list.append(reimbursement_vo)

        return reimbursement_vo_list

    def approve_reimbursement_apply_ma(self, user_id, reimbursement_id, approval_id, status, reimbursement_rejection):
        """
        审批报销申请
        :param user_id: 管理员ID
        :param reimbursement_id: 报销ID
        :param approval_id: 审批ID
        :param status: 审批状态
        :param reimbursement_rejection: 拒绝原因
        :return: 处理结果
        """
        approval = self.get_approval_by_approval_id(approval_id)
        approval.reimbursement_approval_ma = status

        if ReimbursementApprovalEnum.REJECTED.code == status:
            if not reimbursement_rejection:
                raise BusinessException("请填写拒绝原因")
            approval.reimbursement_rejection_ma = reimbursement_rejection

        result = self.update_approval_by_approval_id(
            approval, approval_id)

        if result == 0:
            raise BusinessException("提交信息失败")

        reimbursement_approval_ma = ReimbursementApprovalMa()
        reimbursement_approval_ma.manager_id = user_id
        reimbursement_approval_ma.reimbursement_id = reimbursement_id
        reimbursement_approval_ma.date = datetime.date.today()

        reimbursement_approval_ma_query = ReimbursementApprovalMaQuery()
        reimbursement_approval_ma_query.reimbursement_approval_ma_id = reimbursement_id
        reimbursement_approval_ma_query.manager_id = user_id
        reimbursement_approval_ma_list = self.reimbursement_approval_ma_mapper.select_list(
            ReimbursementApprovalMa, reimbursement_approval_ma_query)

        if not reimbursement_approval_ma_list:
            # 无记录，新增
            result = self.reimbursement_approval_ma_mapper.insert(
                reimbursement_approval_ma)
        else:
            # 有记录，更新
            result = self.reimbursement_approval_ma_mapper.update_by_reimbursement_approval_ma_id(
                reimbursement_approval_ma, reimbursement_approval_ma_list[
                    0].reimbursement_approval_ma_id
            )

        return result

    def get_reimbursement_apply_fi(self, user_id, page_no, page_size):
        """
        获取报销申请（财务审批）
        :param user_id: 用户ID
        :param page_no: 页码
        :param page_size: 每页数量
        :return: 分页结果
        """
        reimbursement_vo_list = []

        reimbursement_statuses = [
            ReimbursementApprovalEnum.UNPROCESSED,
            ReimbursementApprovalEnum.APPROVED,
            ReimbursementApprovalEnum.REJECTED,
            ReimbursementApprovalEnum.HANDLED
        ]

        for status in reimbursement_statuses:
            reimbursement_vo_list.extend(
                self.fetch_reimbursement_vo_s_by_approval_status_fi(status))

        # 去除自己的申请
        reimbursement_vo_list = [
            reimbursement_vo for reimbursement_vo in reimbursement_vo_list if reimbursement_vo.user_id != user_id]

        count = len(reimbursement_vo_list)

        # start = (page_no - 1) * page_size
        # end = start + page_size
        # if end > count:
        #     end = count
        # total_page = count // page_size + (1 if count % page_size != 0 else 0)

        result = PaginationResultVO(
            count, page_size, page_no, 0, reimbursement_vo_list)

        return result

    def fetch_reimbursement_vo_s_by_approval_status_fi(self, status):
        """
        根据审批状态查询报销信息
        :param status: 审批状态
        :return: 报销VO列表
        """
        reimbursement_vo_list = []

        # 查询报销申请状态，出差已被批准，已被经理批准
        approval_query = ApprovalQuery()
        approval_query.travel_approval = TravelApprovalEnum.APPROVED.code
        approval_query.reimbursement_approval_ma = ReimbursementApprovalEnum.APPROVED.code
        approval_query.reimbursement_approval_fi = status.code

        approval_list = self.find_list_by_param(approval_query)
        approval_map = {
            approval.travel_id: approval for approval in approval_list}

        travel_id_list = list(
            set([approval.travel_id for approval in approval_list]))

        if not travel_id_list:
            return reimbursement_vo_list

        # 获取出差申请和对应的用户信息
        travel_list = self.travel_client.get_all_travels_by_id_list(
            travel_id_list)
        travel_map = {travel.travel_id: travel for travel in travel_list}

        user_id_list = list(set([travel.user_id for travel in travel_list]))
        user_list = self.user_client.get_all_users_by_id_list(user_id_list)
        user_map = {user.user_id: user for user in user_list}

        # 获取报销申请信息
        reimbursement_list = self.reimbursement_client.get_reimbursements_by_id_list(
            travel_id_list)

        for reimbursement in reimbursement_list:
            reimbursement_vo = CopyTools.copy(reimbursement, ReimbursementVO)
            reimbursement_vo.reimbursement = (reimbursement.food_cost +
                                              reimbursement.hotel_cost + reimbursement.transport_cost)

            travel = travel_map.get(reimbursement.travel_id)
            reimbursement_vo.travel_reason = travel.travel_reason
            reimbursement_vo.travel_detail = travel.travel_detail
            reimbursement_vo.start_date = travel.start_date
            reimbursement_vo.end_date = travel.end_date

            # 获取财务审批信息
            reimbursement_approval_fi_query = ReimbursementApprovalFiQuery()
            reimbursement_approval_fi_query.reimbursement_id = reimbursement.reimbursement_id
            reimbursement_approval_fi_list = self.reimbursement_approval_fi_mapper.select_list(
                ReimbursementApprovalFi, reimbursement_approval_fi_query)

            if reimbursement_approval_fi_list and reimbursement_approval_fi_list[0].payment > 0:
                reimbursement_vo.payment = reimbursement_approval_fi_list[0].payment
            else:
                reimbursement_vo.payment = None

            user = user_map.get(travel.user_id)
            reimbursement_vo.user_id = user.user_id
            reimbursement_vo.user_name = user.name
            reimbursement_vo.user_phone = user.phone
            reimbursement_vo.user_email = user.email
            reimbursement_vo.position = user.position

            approval = approval_map.get(travel.travel_id)
            reimbursement_vo.approval_id = approval.approval_id
            reimbursement_vo.reimbursement_status = status.code
            reimbursement_vo.reimbursement_status_name = status.msg
            reimbursement_vo.reimbursement_rejection = approval.reimbursement_rejection_fi

            reimbursement_vo_list.append(reimbursement_vo)

        return reimbursement_vo_list

    def approve_reimbursement_apply_fi(self, user_id, reimbursement_id, approval_id,
                                       payment, status, reimbursement_rejection):
        """
        财务审批报销申请
        :param user_id: 财务人员ID
        :param reimbursement_id: 报销ID
        :param approval_id: 审批ID
        :param payment: 财务支付金额
        :param status: 审批状态
        :param reimbursement_rejection: 拒绝原因（如果状态是拒绝）
        :return: 影响的行数
        """
        # 获取审批对象
        approval = self.get_approval_by_approval_id(approval_id)
        approval.reimbursement_approval_fi = status

        # 如果状态是拒绝，检查拒绝原因
        if ReimbursementApprovalEnum.REJECTED.code == status:
            if not reimbursement_rejection:
                raise BusinessException("请填写拒绝原因")
            approval.reimbursement_rejection_fi = reimbursement_rejection

        # 更新审批信息
        result = self.update_approval_by_approval_id(approval, approval_id)
        if result == 0:
            raise BusinessException("提交信息失败")

        # 创建财务审批对象
        reimbursement_approval_fi = ReimbursementApprovalFi()
        reimbursement_approval_fi.finance_id = user_id
        reimbursement_approval_fi.reimbursement_id = reimbursement_id
        reimbursement_approval_fi.payment = payment
        reimbursement_approval_fi.date = datetime.date.today()

        # 查询是否已有该记录
        reimbursement_approval_fi_query = ReimbursementApprovalFiQuery()
        reimbursement_approval_fi_query.reimbursement_id = reimbursement_id
        reimbursement_approval_fi_query.finance_id = user_id
        reimbursement_approval_fi_list = self.reimbursement_approval_fi_mapper.select_list(
            ReimbursementApprovalFi, reimbursement_approval_fi_query)

        if not reimbursement_approval_fi_list:
            # 无记录，新增
            result = self.reimbursement_approval_fi_mapper.insert(
                reimbursement_approval_fi)
        else:
            # 有记录，更新
            result = self.reimbursement_approval_fi_mapper.update_by_reimbursement_approval_fi_id(
                reimbursement_approval_fi, reimbursement_approval_fi_list[0].reimbursement_approval_fi_id)

        return result

    def get_by_travel_id(self, travel_id):
        """
        根据 travel_id 获取对应的审批记录。
        :param travel_id: 出差 ID
        :return: 审批记录信息字典或 None
        """
        print("ApprovalService get_approval_by_travel_id")
        print(f"travel_id: {travel_id}")

        # 直接通过 travel_id 查找审批记录
        approval = self.approval_mapper.select_approve_by_travel_id(travel_id)

        # 如果查询返回为空，说明没有找到记录
        if not approval:
            return None

        return approval  # 返回审批记录